<?php

	$host = "localhost";
	$user = "deploy";
	$password = "deploy";
	$task_table =  "deploy_task";
	$app_table = "app_info";
	$database = "k9deploy_new";
	
	$link = mysql_connect("$host","$user","$password");
	if (!$link) {
	    die('Could not connect: ' . mysql_error());
	}
	echo 'Connected successfully';
	
	mysql_select_db($database);
	function get_app_info($appid,$app_table){
		$sql = "select * from $app_table where id = '$appid';";
		mysql_query("set names utf8;");
		$result = mysql_query($sql);
		while($arr=mysql_fetch_assoc($result)){
			return $arr;
		}
	}
		
	function update_status($task_table,$appid){
		$sql = "update $task_table set status = '1' where appid = '$appid' order by id desc limit 1;";		
		mysql_query($sql);
	}


	$sql = "select * from $task_table where status=0 limit 1;";
	echo "select * from $task_table where status=0 limit 1;";
	mysql_query("set names utf8;");
	$result = mysql_query($sql);
	while($arr=mysql_fetch_assoc($result)){
		$env = $arr['env'];
		var_dump($env);
		$appid = $arr['appid'];
		$app_info = get_app_info($appid,$app_table);
		$app_name = $app_info['app_name'];
		$git_url = $app_info['git_url'];
		$ci_flag = $app_info['ci_flag'];	
		$nci_db_flag = $app_info['nci_db_flag'];
		$back_commit = $arr['back_commit'];
	}	

	if(!empty($app_name)){
		update_status($task_table,$appid);
		$now_time=date("Y-m-d H:i:s"); 
		system("echo ${now_time} ${app_name} > /tmp/${app_name}_deploy_log;bash -x deploy.sh {$app_name} {$env} {$git_url} {$back_commit} {$ci_flag} {$nci_db_flag} >> /tmp/${app_name}_deploy_log 2>&1;chmod 777 /tmp/${app_name}_deploy_log");
	}else{
		system("echo 'no没有要发布的程序。' >> /tmp/deploy_error_log");
		exit();
	}
?>
